package com.briup.ch13;

import java.lang.reflect.Field;

/**
 * @Author briup-adam
 * @Date 2023/10/31 上午8:01
 * @Description 通过反射获取属性  并进行赋值与取值
 *
 **/

public class FieldDemo {
    public static void main(String[] args) {
        Class<Cat> catClass = Cat.class;
        //获取所有公共属性
        Field[] fields = catClass.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        System.out.println("====================");
        //获取所有属性、
        fields = catClass.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        //获取指定的公共属性
        try {
            Field kind = catClass.getField("kind");
            System.out.println(kind);
//            获取属性的类型
            Class<?> type = kind.getType();
            System.out.println(type);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        //获取指定的属性
        try {
            Field name = catClass.getDeclaredField("name");
            Class<?> type = name.getType();
            System.out.println(type);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        System.out.println("-----------------------");

        try {
            Cat cat = catClass.newInstance();
            Field name = catClass.getDeclaredField("name");
            //属性的赋值
            name.setAccessible(true);
            name.set(cat,"学长");

            Field age = catClass.getDeclaredField("age");
            age.setAccessible(true);
            age.set(cat,10);
            //  属性的取值
            Object o = name.get(cat);
            System.out.println(o);
            System.out.println(cat);

            //静态属性的取值和赋值
            Field uid = catClass.getDeclaredField("serialVersionUID");
            Object o1 = uid.get(cat);
            System.out.println(o1);
            Object o2 = uid.get(null);
            System.out.println(o2);
            //反射不能对final修饰的常量 进行赋值
            uid.set(cat,41L);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
